<?php
declare (strict_types=1);

namespace Xtsb\Cims\Middleware;

use Xtsb\Cims\Exception\ApiErrorDesc;
use Xtsb\Cims\Exception\ApiException;

use think\facade\Cache;
use think\facade\Db;

class  Auth
{
  /**
   * 当前模块名
   * @var string
   */
  protected $module;

  /**
   * 当前控制器名
   * @var string
   */
  protected $controller;

  /**
   * 当前操作名
   * @var string
   */
  protected $action;

  protected $rules; //用户拥有的权限id

  /**
   * 处理请求
   * @param $request
   * @param \Closure $next
   * @return mixed|void
   */
  public function handle($request, \Closure $next)
  {
    //
    $token = $request->header('user-token');
    if (!$token) {
      throw new ApiException(ApiErrorDesc::TOKEN_REQUIRE);
    }
//    $this->setTheme($request);//获取模块、控制器、操作方法

    $userToken = json_decode(base64_decode($token));
    \think\facade\Log::channel('cims')->info('数据头结果 ：{data}', ['data' => json_encode($userToken)]);

    $userInfo = $userToken->user_info;
    $routeInfo = $userToken->route;
    $url = $routeInfo->controller . '/' . $routeInfo->action;

    if (!isset($userInfo->uid)) {
      throw new ApiException(ApiErrorDesc::LOGIN_USER_ERROR);
    }

    $uid = $userInfo->uid;//用户身份id

//        $cacheName = $uid . '_' . $url . '_' . ($request->server()['QUERY_STRING'] ?? null);
    $cacheName = $uid . '_' . $url;
    if (!in_array(request()->ip(), ['127.0.0.1', '::1'])) {
      if (Cache::store('redis')->get($cacheName)) {

        throw new ApiException(ApiErrorDesc::DATA_PROCESSED);
      } else if (config('app.access_frequency_setting') && in_array($request->method(), config('app.access_frequency_setting_method'))) {
//                $second = in_array($request->method(), ['PUT', 'POST']) ? 5 : 1;//5秒  1秒
//                //缓存$second秒后过期
//                Cache::store('redis')->set($cacheName, 1, $second);
        Cache::store('redis')->set($cacheName, 1, 15);
      }
    }
    $request->cacheName = $cacheName;

    $request->userInfo = $userToken->user_info;
    $request->rules = self::getRules($userToken->rules);//Db::name('auth_rule')->whereIn('id', $rules)->column('url')

    $request->moduleName = $routeInfo->module;//模块名
    $request->controllerName = $routeInfo->controller;//控制器名
    $request->actionName = $routeInfo->action;//操作方法

    $request->httpUserAgent = $request->header('Http-User-Agent');//访问系统的终端系统

    return $next($request);
  }

  /**
   * Notes: 获取权限路径
   */
  private function getRules($rules)
  {
    return Db::name('auth_rule')->whereIn('id', $rules)
      ->whereOr('is_admin', 2)//开放权限
      ->whereNotNull('url')
      ->whereRaw('LENGTH(TRIM(url))>0')
      ->order('url')
      ->column('url');
  }

  /**
   * Notes:获取模块名、控制器名、操作方法名
   * author: chen
   * DateTime: 2022/2/9 9:13
   * @param $request
   */
//  private function setTheme($request)
//  {
//    //获取控制器名称
//    $route = $request->rule()->getName();
//
//    if ($route === 'app\Http\Controllers\:controller_nameController@:action_name') {
//      //动态路由
//      $info = explode('/', str_replace('/api/v1/xtsb/', '', $request->server()['REDIRECT_URL'] ?? $request->server()['PATH_INFO']));
//      $this->action = $info[1];
//      $this->controller = $info[0];
//      $this->module = $info[2];
//    } else if (strpos($route, '/')) {
//      //资源路由
//      $info = explode('\\', str_replace('/', '\\', $route));
//      $this->action = $info[4];
//      $this->controller = str_replace('Controller', '', $info[3]);
//      $this->module = null;
//    } else if (strpos($route, '@')) {
//      //操作方法路由
//      $info = explode('\\', str_replace('@', '\\', $route));
//      $this->action = $info[4];
//      $this->controller = str_replace('Controller', '', $info[3]);
//      $this->module = null;
//    } else {
//
//      throw new ApiException(ApiErrorDesc::TOKEN_REQUIRE);
//    }
//  }
}

